import axios, { AxiosRequestConfig, AxiosResponse, AxiosError, AxiosInstance } from "axios";
import store from "@src/store";
import { message as Message } from "antd";
import BaseConfig from "./config";

const { httpURL } = BaseConfig;
const axiosInstance: AxiosInstance = axios.create({
  // 默认的请求头
  baseURL: httpURL,
});

/**
 * 添加请求拦截器
 */
axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const { isLogin, Authorization } = store.getState().login;
    if (isLogin) {
      config.headers.Authorization = Authorization;
    }
    return config;
  },
  (error: AxiosError) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
/**
 * 添加响应拦截器
 */
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    console.log(response);
    const { status, data = {} } = response;
    const { code, message } = data;
    if (code === 1) {
      return data.data;
    }
    Message.error(message);
    return Promise.reject(response);
  },
  async (error: AxiosError) => {
    // 对响应错误做点什么
    console.log(error.response);
    const { status, data } = error.response;
    switch (status) {
      case 401:
        // token失效
        await store.dispatch({ type: "login/logout" });
        break;
      case 403:
        // 没有权限
        break;
      case 500:
        // 服务端错误
        break;
      case 503:
        // 服务端错误
        break;
      default:
        break;
    }
    Message.error(data.message);
    return Promise.reject(error.response);
  }
);

export default axiosInstance;
